<?php

ini_set('max_execution_time', 300);

class ExtractMovieDetails {

    var $title;
    var $genre;
    var $year;
    var $poster;
    var $cast;
    var $director;
    var $plot;
    var $rating;
    var $runtime;
    var $writer;
    var $location;
    var $imdbid;
    var $filename;
    var $dirname;
    var $ext;
    var $ischanged;
    var $test;
    var $moviefile;
    var $filetime;
    var $nfotime;
    var $watched;

    function __construct($moviefile, $ischanged = "0", $id = false) {
        if ($ischanged == "1") {
            $this->ischanged = "1";
        } else {
            $this->ischanged = "0";
        }
        $this->moviefile = $moviefile;
        if ($id) {
            $this->getimdbid($id);
        } else {
            $this->getimdbid();
        }
        $this->filetime = exec('/usr/bin/busybox stat -c %Y ' . escapeshellarg($this->moviefile));
    }

    private function GetMovieInfo() {
        $file = $this->dirname . '/retrieved.xml';
        if ($this->ischanged == "1") {
            if (file_exists($file)) {
                unlink($file);
            }
        }
        $watched = $this->dirname . '/.watched';
        if (file_exists($watched)) {
            $this->watched = "1";
        } else {
            $this->watched = NULL;
        }
        if (!file_exists($file)) {
            if ($this->imdbid != "0") {
                include_once ('imdb.php');
                $oIMDB = new IMDB($this->imdbid);
                if ($oIMDB->isReady) {
                    $this->title = htmlspecialchars(strip_tags($oIMDB->getTitle()), ENT_QUOTES);
                    $this->genre = $oIMDB->getGenre();
                    $this->year = $oIMDB->getYear();
                    $poster = $oIMDB->getPoster();
                    if ($poster == "n/A") {
                        $poster = "/usr/local/etc/www/Jukebox/images/nofolder.jpg";
                    }
                    $this->poster = base64_encode(file_get_contents($poster));
                    $this->cast = htmlspecialchars($oIMDB->getCastAndCharacter(5), ENT_QUOTES);
                    $this->director = htmlspecialchars($oIMDB->getDirector(), ENT_QUOTES);
                    $this->plot = htmlspecialchars(strip_tags($oIMDB->getPlot()), ENT_QUOTES);
                    $this->rating = $oIMDB->getRating();
                    $this->runtime = htmlspecialchars($oIMDB->getRuntime(), ENT_QUOTES);
                    $this->writer = htmlspecialchars($oIMDB->getWriter(), ENT_QUOTES);
                    $this->location = htmlspecialchars($oIMDB->getLocation(), ENT_QUOTES);
                }
            } else {
                $this->title = "no imdbid";
                $poster = "/usr/local/etc/www/Jukebox/images/nofolder.jpg";
            }
            $xml = new SimpleXMLElement('<movieinfo></movieinfo>');
            $xml->imdbid = $this->imdbid;
            $xml->title = $this->title;
            $xml->genre = $this->genre;
            $xml->year = $this->year;
            $xml->plot = $this->plot;
            $xml->rating = $this->rating;
            $xml->cast = $this->cast;
            $xml->director = $this->director;
            $xml->runtime = $this->runtime;
            $xml->writer = $this->writer;
            $xml->location = $this->location;
            $xml->poster = $this->poster;
            // $xml->poster2 = $image2;
            $dom = new DOMDocument('1.0');
            $dom->preserveWhiteSpace = false;
            $dom->formatOutput = true;
            $dom->loadXML($xml->asXML());
            $exit = $dom->saveXML();
            file_put_contents($file, $exit);
            file_put_contents($this->dirname . '/folder.jpg', file_get_contents($poster));
        } else {
            $xml = simplexml_load_file($file);
            $this->imdbid = $xml->imdbid[0];
            $this->title = $xml->title[0];
            $this->genre = $xml->genre[0];
            $this->year = $xml->year[0];
            $this->plot = $xml->plot[0];
            $this->rating = $xml->rating[0];
            $this->cast = $xml->cast[0];
            $this->director = $xml->director[0];
            $this->runtime = $xml->runtime[0];
            $this->writer = $xml->writer[0];
            $this->location = $xml->location[0];
            $this->poster = $xml->poster[0];
            $poster = base64_decode($this->poster);
            file_put_contents($this->dirname . '/folder.jpg', $poster);
        }
        //$output = $this->nmr . ". " . $dirname;
        //file_put_contents("/usr/local/etc/www/test/imbd_db", $output);
        if ($poster2 == "1") {
            CreateMoviePoster($poster, $this->title, $this->year, $this->rating, $this->runtime, $this->genre, $this->director, $this->writer, $this->location, $this->cast, $this->plot);
        }
    }

    function CreateMoviePoster($poster, $title, $year, $rating, $runtime, $genre, $director, $writer, $location, $cast, $plot) {
        $save = $this->dirname . '/poster.jpg';
        $rating = $rating . " /10";
        $im = imagecreatefromjpeg("background.jpg");
        $white = imagecolorallocate($im, 255, 255, 255);
        $font = '/usr/local/bin/Resource/font/arialbold.ttf';
        $fontSize = '16';
        $cast = wordwrap($cast, 55, "\n", true);
        $plot = wordwrap($plot, 105, "\n", true);
        //imagestring($im, $font, $px, 20, $string, $black);
        imagestring($im, 5, 150, 70, $title, $white);
        //imagettftext($im, 32, 0, 150, 70, $white, $font, $title);
        imagettftext($im, 24, 0, 675, 185, $white, $font, $year);
        imagettftext($im, 24, 0, 540, 185, $white, $font, $rating);
        imagettftext($im, 24, 0, 840, 185, $white, $font, $runtime);
        imagettftext($im, $fontSize, 0, 620, 233, $white, $font, $genre);
        imagettftext($im, $fontSize, 0, 620, 263, $white, $font, $director);
        imagettftext($im, $fontSize, 0, 620, 294, $white, $font, $writer);
        imagettftext($im, $fontSize, 0, 620, 325, $white, $font, $location);
        imagettftext($im, 12, 0, 620, 360, $white, $font, $cast);
        imagettftext($im, $fontSize, 0, 115, 515, $white, $font, $plot);
        $watermark = imagecreatefromjpeg($poster);
        $watermark_width = imagesx($watermark);
        $watermark_height = imagesy($watermark);
        imagecopymerge($im, $watermark, 105, 123, 0, 0, $watermark_width, $watermark_height, 100);
        imagejpeg($im, $save);
        imagedestroy($im);
        imagedestroy($watermark);
    }
    function extractName($dirname) {
	$rem_b = preg_replace('/^.*\/\s*/', '', $dirname);
	$replace_dots = preg_replace("/\./", " ", $rem_b);
	$clean_name = preg_replace("/(?:HDTV(.*)|\[etrg\]|web-dl(.*)|dvdscr(.*)|blu-ray(.*)|\w{2,3}rip(.*))|(?:\(?\[?\d{4}\]?\)?\w?)(.*)|(?:\d{3,4}p)|(?:AC\d)/i", "", $replace_dots);
	return $clean_name;
    }
    public function getimdbid($id = false) {
        $parts = pathinfo($this->moviefile);
        $this->dirname = $parts['dirname'];
        //$basename = $parts['basename'];
        $this->filename = $parts['filename'];
        $this->ext = $parts['extension'];
        $escapedBracketPath = str_replace('[', '\[', $this->dirname);
        $escapedBracketPath = str_replace(']', '\]', $escapedBracketPath);
        $escapedBracketPath = str_replace('\[', '[[]', $escapedBracketPath);
        $escapedBracketPath = str_replace('\]', '[]]', $escapedBracketPath);
        $nfo = glob($escapedBracketPath . '/*.[nN][fF][oO]', GLOB_BRACE);
        if ($nfo[0] == null) {
	  $this->imdbid = $this->extractName($this->dirname);
	  //$this->imdbid = "0";
            $this->nfotime = "0";
        } else {
            $this->nfotime = filectime($nfo[0]);
            $content = file_get_contents($nfo[0]);
            $finfo = finfo_open(FILEINFO_MIME_ENCODING);
            if (finfo_file($finfo, $nfo[0]) === "utf-16le") {
                $content = iconv('utf-16le', 'UTF-8', $content);
            }
            if (preg_match("/tt(?P<digit>\d+)/", $content, $matches)) {
                $this->imdbid = $matches[0];
            } else {
             $this->imdbid = $this->extractName($this->dirname);
             //$this->imdbid = "0";
            }
        }
        if ($id) {
            return $this->imdbid;
        } else {
            if ($this->imdbid != "0") {
                $this->GetMovieInfo();
            }
        }
    }

}

?>